#define  _CRT_SECURE_NO_WARNINGS
#include "tree.h"
#include "Queue.h"

BTNode* BuynewNode(TreeDataType x)
{
	BTNode* newnode = (BTNode*)malloc(sizeof(BTNode));
	assert(newnode);
	newnode->data = x;
	newnode->left = newnode->right = NULL;
	return newnode;
}

void  PreOrder(BTNode* root)
{
	if (root == NULL)
	{
		return ;
	}
	printf("%d ", root->data);
	PreOrder(root->left);
	PreOrder(root->right);
}

void  InOrder(BTNode* root)
{
	if (root == NULL)
	{
		return;
	}
	PreOrder(root->left);
	printf("%d ", root->data);
	PreOrder(root->right);
}

void  PostOrder(BTNode* root)
{
	if (root == NULL)
	{
		return;
	}
	PreOrder(root->left);
	PreOrder(root->right);
	printf("%d ", root->data);
}

int BinaryTreeSize(BTNode* root)
{
	if (NULL == root)
	{
		return 0;
	}
	return 1 + BinaryTreeSize(root->left) + BinaryTreeSize(root->right);
}

int BinaryTreeLeafSize(BTNode* root)
{
	if (NULL == root)
	{
		return 0;
	}
	if (root->left == NULL && root->right == NULL)
	{
		return 1;
	}
	return BinaryTreeLeafSize(root->left) + BinaryTreeLeafSize(root->right);
}

int BinaryTreeLevelKSize(BTNode* root, int k)
{
	if (NULL == root)
	{
		return 0;
	}
	if (k == 1)
	{
		return 1;
	}
	return BinaryTreeLevelKSize(root->left, k - 1) + BinaryTreeLevelKSize(root->right, k - 1);
}

int BinaryTreeDepth(BTNode* root)
{
	if (NULL == root)
	{
		return 0;
	}
	int leftdep = BinaryTreeDepth(root->left);
	int rightdep = BinaryTreeDepth(root->right);
	return leftdep >= rightdep ? 1 + BinaryTreeDepth(root->left) : 1 + BinaryTreeDepth(root->right);
}

BTNode* BinaryTreeFind(BTNode* root, TreeDataType x)
{
	if (NULL == root)
	{
		return NULL;
	}
	if (x == root->data)
	{
		return root;
	}
	BTNode* leftfind = BinaryTreeFind(root->left, x);
	if(leftfind)
	{
		return leftfind;
	}
	BTNode* rightfind = BinaryTreeFind(root->right, x);
	if (rightfind)
	{
		return rightfind;
	}
	return NULL;
}

void BinaryTreeDestory(BTNode** root)
{
	if (NULL == *root)
	{
		return ;
	}
	BinaryTreeDestory(&((*root)->left));
	BinaryTreeDestory(&((*root)->right));
	free(*root);
	*root = NULL;
}

void BinaryLevelOrder(BTNode* root)
{
	Queue p;
	InitQueue(&p);
	QueuePush(&p, root);
	while (!BoolEmpty(&p))
	{
		BTNode* front = QueueFront(&p);
		printf("%d->", front->data);
		QueuePop(&p);
		if (front->left)
		{
			QueuePush(&p, front->left);
		}
		if (front->right)
		{
			QueuePush(&p, front->right);
		}
	}
}

bool BinaryTreeComplete(BTNode* root)
{
	Queue p;
	InitQueue(&p);
	QueuePush(&p, root);
	while (!BoolEmpty(&p))
	{
		BTNode* front = QueueFront(&p);
		QueuePop(&p);
		if (front == NULL)
		{
			break;
		}
		QueuePush(&p, front->left);
		QueuePush(&p, front->right);
	}
	while (!BoolEmpty(&p))
	{
		BTNode* front = QueueFront(&p);
		if (front != NULL)
		{
			QueueDestroy(&p);
			return false;
		}
		QueuePop(&p);
	}
	QueueDestroy(&p);
	return true;
}